package com.tjcd.project.library_base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Process;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;
import androidx.work.WorkManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.hjq.http.EasyConfig;
import com.hjq.toast.Toaster;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jeremyliao.liveeventbus.logger.Logger;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.tencent.mmkv.MMKV;
import com.tjcd.project.library_base.base.easyhttpnet.EasyHttpInterceptor;
import com.tjcd.project.library_base.base.easyhttpnet.RequestServer;
import com.tjcd.project.library_base.base.network.NetInterceptor;
import com.tjcd.project.library_base.base.network.RequestHandler;
import com.tjcd.project.library_base.base.network.SSLSocketClient;
import com.tjcd.project.library_base.push.mqtt.MqttConfig;
import com.tjcd.project.library_base.room.utils.RoomUtil;

import org.jetbrains.annotations.NotNull;

import java.net.SocketTimeoutException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import me.jessyan.autosize.AutoSizeConfig;
import okhttp3.OkHttpClient;

/**
 * @Author: jiangKunKun
 * @CreateDate: 2023/3/2
 * @Description:
 * @SpittingGrooves
 */
public class BaseApplication extends MultiDexApplication implements Application.ActivityLifecycleCallbacks {

    private List<Activity> activityList;

    /**
     * 上下文
     */
    public static BaseApplication mContext;
    /**
     * Application单例
     */
    public static BaseApplication getInstance() {
        if (mContext == null) {
            synchronized (BaseApplication.class) {
                if (mContext == null) {
                    mContext = new BaseApplication();
                }
            }
        }
        return mContext;
    }

    /**
     * static 代码段可以防止内存泄露
     */
    static {
        // 设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white_FFFFFF, R.color.black_000000);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        // 设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    /**
     * 初始化基础配偶之
     */
    @Override
    public void onCreate() {
        super.onCreate();

        if (shouldInit()) {
            mContext = this;
//            Density.setDensity((Application) getApplicationContext(), 360);  // 屏幕适配
            AutoSizeConfig.getInstance()
                    .setDesignWidthInDp(540)
                    .setDesignHeightInDp(960);
            AutoSizeConfig.getInstance().setCustomFragment(true);

            MultiDex.install(this);

//            UMConfigure.preInit(this, "key", "umeng");
            initDebug();
            MMKV.initialize(this);
            // 初始化数据库
            RoomUtil.initDao();

            // LiveEventBus 配置
            LiveEventBus
                    .config()
                    .autoClear(true)
                    .setLogger(new Logger() {
                        @Override
                        public void log(Level level, String msg) {
                            LogUtils.e("LiveEventBus msg = " + msg);
                        }

                        @Override
                        public void log(Level level, String msg, Throwable th) {
                        }
                    })
                    .lifecycleObserverAlwaysActive(true);

            // 初始化 Toast 框架
            Toaster.init(this);

            initActivityLifecycle();

            initialization();

            RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Throwable {
                    if (throwable instanceof SocketTimeoutException) {
                        // 处理超时异常
                        LogUtils.e("SocketTimeoutException: " + throwable.getMessage());
                    } else {
                        // 其他异常处理
                        LogUtils.e("Unhandled exception: " + throwable.getMessage());
                    }
                }
            });
        }
    }

    private void initActivityLifecycle() {
        ActivityUtils.addActivityLifecycleCallbacks(new Utils.ActivityLifecycleCallbacks(){
            @Override
            public void onActivityCreated(@NonNull @NotNull Activity activity) {
                super.onActivityCreated(activity);
            }

            @Override
            public void onActivityStarted(@NonNull @NotNull Activity activity) {
                super.onActivityStarted(activity);
            }

            @Override
            public void onActivityResumed(@NonNull @NotNull Activity activity) {
                super.onActivityResumed(activity);
            }

            @Override
            public void onActivityPaused(@NonNull @NotNull Activity activity) {
                super.onActivityPaused(activity);
            }

            @Override
            public void onActivityStopped(@NonNull @NotNull Activity activity) {
                super.onActivityStopped(activity);
            }

            @Override
            public void onActivityDestroyed(@NonNull @NotNull Activity activity) {
                super.onActivityDestroyed(activity);
            }

            @Override
            public void onLifecycleChanged(@NonNull @NotNull Activity activity, Lifecycle.Event event) {
                super.onLifecycleChanged(activity, event);
            }
        });
        registerActivityLifecycleCallbacks(this);
    }


    /**
     * 用户同意使用app后 初始化各种SDK信息
     */
    public void initialization(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        // 使用自定义的 SSLSocketFactory 和 X509TrustManager
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getTrustManager());
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier()); // 取消验证主机名

        builder.connectTimeout(30, TimeUnit.SECONDS); // 连接超时的时间
        builder.readTimeout(30, TimeUnit.SECONDS); // 连接的读取超时时间
        builder.writeTimeout(30, TimeUnit.SECONDS); // 写入超时时间
        builder.addInterceptor(new NetInterceptor()); // 添加拦截器

        EasyConfig.with(builder.build())
                // 是否打印日志
                .setLogEnabled(true)
                // 设置服务器配置（必须设置）
                .setServer(new RequestServer())
                // 设置请求处理策略（必须设置）
                .setHandler(new RequestHandler(this))
                // 设置请求重试次数
                .setRetryCount(3)
                // 添加拦截器
                .setInterceptor(new EasyHttpInterceptor())
                // 添加全局请求参数
                //.addParam("token", "6666666")
                // 添加全局请求头
                //.addHeader("time", "20191030")
                // 启用配置
                .setLogEnabled(true)
                .into();
        // 添加全局请求参数 addParam
        // 移除全局请求参数 removeParam
        // 添加全局请求头 addHeader
        // 移除全局请求头 removeHeader
//        EasyConfig.getInstance()
//                .addParam("token", "123");

    }

    /**
     * 解决APP启动走两次appLication
     * @return
     */
    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 初始化debug模式
     */
    private void initDebug() {
//        if (SugarUrls.debug) { // debug模式 切换debug模式
//            SugarUrls.baseUrl = SugarUrls.baseDeBugUrl;
//        }
    }

    /**
     * 低内存时 释放其他资源
     */
    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    /**
     * 禁止修改字体大小
     * @return
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 禁止修改字体大小
     * @return
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // 非默认值
        if (newConfig.fontScale != 1){
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
//        if (activityList != null) {
//            activityList.remove(activity);
//        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        // 应用关闭时取消 WorkManager 的周期性任务
        cancelMqttWorker();
    }


    private void cancelMqttWorker() {
        WorkManager.getInstance(this).cancelUniqueWork(MqttConfig.WORKER_NAME);
    }
}
